#include "uart.h"
#include "hal_rcc.h"
#include "hal_gpio.h"
#include "hal_uart.h"
#include "hal_common.h"
#include "clock_init.h"
#include <stdio.h>
#include "shell_port.h"

static void BOARD_InitUartPins(void)
{
    /* Pb6 - UART1_TX. */
    GPIO_Init_Type gpio_init;
    gpio_init.Pins  = CONSOLE_TX_GPIO_PIN;
    gpio_init.PinMode  = GPIO_PinMode_AF_PushPull;
    gpio_init.Speed = GPIO_Speed_50MHz;
    GPIO_Init(CONSOLE_GPIO_PORT, &gpio_init);
    GPIO_PinAFConf(CONSOLE_GPIO_PORT, gpio_init.Pins, GPIO_AF_7);

    /* Pb7 - UART1_RX. */
    gpio_init.Pins  = CONSOLE_RX_GPIO_PIN;
    gpio_init.PinMode  = GPIO_PinMode_In_Floating;
    gpio_init.Speed = GPIO_Speed_50MHz;
    GPIO_Init(CONSOLE_GPIO_PORT, &gpio_init);
    GPIO_PinAFConf(CONSOLE_GPIO_PORT, gpio_init.Pins, GPIO_AF_7);
}

void BOARD_InitDebugConsole(void)
{
    UART_Init_Type uart_init;
	BOARD_InitUartPins();

    uart_init.ClockFreqHz   = CLOCK_APB2_FREQ;
    uart_init.BaudRate      = 115200U;
    uart_init.WordLength    = UART_WordLength_8b;
    uart_init.StopBits      = UART_StopBits_1;
    uart_init.Parity        = UART_Parity_None;
    uart_init.XferMode      = UART_XferMode_RxTx;
    uart_init.HwFlowControl = UART_HwFlowControl_None;
    uart_init.XferSignal    = UART_XferSignal_Normal;
    uart_init.EnableSwapTxRxXferSignal = false;
    UART_Init(BOARD_DEBUG_UART_PORT, &uart_init);
    
    /* Enable RX interrupt. */
    UART_EnableInterrupts(BOARD_DEBUG_UART_PORT, UART_INT_RX_DONE, true);
    NVIC_EnableIRQ(UART1_IRQn);

    UART_Enable(BOARD_DEBUG_UART_PORT, true);
}

int _write (int fd, char *pBuffer, int size)
{
	uint32_t i;
	for (i = 0; i < size; i++)
	{
	    while ( 0u == (UART_STATUS_TX_EMPTY & UART_GetStatus(UART1)) )
        {}
        UART_PutData(UART1, (uint8_t)(pBuffer[i]));
	}
	return size;
}

uint8_t recv_buf = 0;

void app_uart_rx_isr_hook(void)
{
    if (   (0u != (UART_INT_RX_DONE & UART_GetEnabledInterrupts(BOARD_DEBUG_UART_PORT)))
        && (0u != (UART_INT_RX_DONE & UART_GetInterruptStatus(BOARD_DEBUG_UART_PORT))) )
    {
        recv_buf = UART_GetData(BOARD_DEBUG_UART_PORT); /* read data to clear rx interrupt bits. */

        //调用shell处理数据的接口
		shellHandler(&shell, recv_buf);
    }
}

/* BOARD_DEBUG_UART_IRQHandler ISR entry. */
void UART1_IRQHandler(void)
{
    app_uart_rx_isr_hook();
}

	
